{% extends "base.html" %}

{% block title %}异步功能演示 - 提示词管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1>
                <i class="bi bi-lightning"></i> 
                异步功能演示
            </h1>
            <a href="{{ url_for('index') }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> 返回首页
            </a>
        </div>
    </div>
</div>

<!-- 状态显示区域 -->
<div id="statusArea" class="mb-4"></div>

<div class="row">
    <div class="col-md-6">
        <!-- 异步备份 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-cloud-upload"></i> 异步备份
                </h5>
            </div>
            <div class="card-body">
                <p class="card-text">在后台异步执行数据备份操作，不会阻塞用户界面。</p>
                <button type="button" class="btn btn-primary" onclick="startAsyncBackup()">
                    <i class="bi bi-play"></i> 开始备份
                </button>
            </div>
        </div>

        <!-- 异步搜索 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-search"></i> 异步搜索
                </h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="searchQuery" class="form-label">搜索关键词</label>
                    <input type="text" class="form-control" id="searchQuery" placeholder="输入搜索关键词">
                </div>
                <button type="button" class="btn btn-success" onclick="startAsyncSearch()">
                    <i class="bi bi-play"></i> 开始搜索
                </button>
            </div>
        </div>

        <!-- 异步导入 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-upload"></i> 异步导入
                </h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="importTitle" class="form-label">导入标题</label>
                    <input type="text" class="form-control" id="importTitle" placeholder="输入导入标题">
                </div>
                <div class="mb-3">
                    <label for="importContent" class="form-label">导入内容</label>
                    <textarea class="form-control" id="importContent" rows="4" placeholder="输入要导入的内容"></textarea>
                </div>
                <button type="button" class="btn btn-warning" onclick="startAsyncImport()">
                    <i class="bi bi-play"></i> 开始导入
                </button>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <!-- 任务状态 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-list-task"></i> 任务状态
                </h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2 mb-3">
                    <button type="button" class="btn btn-info" onclick="refreshTasks()">
                        <i class="bi bi-arrow-clockwise"></i> 刷新任务列表
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="manualReload()">
                        <i class="bi bi-arrow-repeat"></i> 手动重载数据
                    </button>
                </div>
                <div id="tasksList">
                    <p class="text-muted">暂无任务</p>
                </div>
            </div>
        </div>

        <!-- 热重载状态 -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-thermometer-half"></i> 热重载状态
                </h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    <strong>热重载已启用</strong><br>
                    系统会自动监听以下文件的变化：
                    <ul class="mt-2 mb-0">
                        <li>Python文件 (*.py)</li>
                        <li>模板文件 (*.html)</li>
                        <li>数据文件 (data目录)</li>
                    </ul>
                </div>
                <p class="small text-muted">
                    当检测到文件变化时，系统会自动重新加载相关数据，无需重启服务。
                </p>
            </div>
        </div>
    </div>
</div>

<script>
let activeTasks = new Set();

// 显示状态消息
function showStatus(message, type = 'info') {
    const statusArea = document.getElementById('statusArea');
    const alertClass = `alert-${type}`;
    const icon = type === 'success' ? 'check-circle' : 
                type === 'danger' ? 'exclamation-triangle' : 'info-circle';
    
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show`;
    alert.innerHTML = `
        <i class="bi bi-${icon}"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    statusArea.appendChild(alert);
    
    // 5秒后自动移除
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}

// 异步备份
async function startAsyncBackup() {
    try {
        const response = await fetch('/api/async/backup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        if (result.success) {
            showStatus(`备份任务已启动，任务ID: ${result.task_id}`, 'success');
            activeTasks.add(result.task_id);
            monitorTask(result.task_id);
        } else {
            showStatus(`备份失败: ${result.error}`, 'danger');
        }
    } catch (error) {
        showStatus(`请求失败: ${error.message}`, 'danger');
    }
}

// 异步搜索
async function startAsyncSearch() {
    const query = document.getElementById('searchQuery').value;
    
    try {
        const response = await fetch('/api/async/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ query })
        });
        
        const result = await response.json();
        if (result.success) {
            showStatus(`搜索任务已启动，任务ID: ${result.task_id}`, 'success');
            activeTasks.add(result.task_id);
            monitorTask(result.task_id);
        } else {
            showStatus(`搜索失败: ${result.error}`, 'danger');
        }
    } catch (error) {
        showStatus(`请求失败: ${error.message}`, 'danger');
    }
}

// 异步导入
async function startAsyncImport() {
    const title = document.getElementById('importTitle').value;
    const content = document.getElementById('importContent').value;
    
    if (!content.trim()) {
        showStatus('请输入导入内容', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/async/import', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ title, content })
        });
        
        const result = await response.json();
        if (result.success) {
            showStatus(`导入任务已启动，任务ID: ${result.task_id}`, 'success');
            activeTasks.add(result.task_id);
            monitorTask(result.task_id);
        } else {
            showStatus(`导入失败: ${result.error}`, 'danger');
        }
    } catch (error) {
        showStatus(`请求失败: ${error.message}`, 'danger');
    }
}

// 监控任务状态
async function monitorTask(taskId) {
    const checkStatus = async () => {
        try {
            const response = await fetch(`/api/tasks/${taskId}`);
            const status = await response.json();
            
            if (status.status === 'completed') {
                showStatus(`任务 ${taskId} 完成: ${JSON.stringify(status.result)}`, 'success');
                activeTasks.delete(taskId);
                refreshTasks();
            } else if (status.status === 'failed') {
                showStatus(`任务 ${taskId} 失败: ${status.error}`, 'danger');
                activeTasks.delete(taskId);
                refreshTasks();
            } else if (status.status === 'running') {
                // 继续监控
                setTimeout(checkStatus, 1000);
            }
        } catch (error) {
            console.error('监控任务失败:', error);
        }
    };
    
    checkStatus();
}

// 刷新任务列表
async function refreshTasks() {
    try {
        const response = await fetch('/api/tasks');
        const tasks = await response.json();
        
        const tasksList = document.getElementById('tasksList');
        
        if (Object.keys(tasks).length === 0) {
            tasksList.innerHTML = '<p class="text-muted">暂无任务</p>';
            return;
        }
        
        let html = '';
        for (const [taskId, task] of Object.entries(tasks)) {
            const statusClass = task.status === 'completed' ? 'success' : 
                              task.status === 'failed' ? 'danger' : 'primary';
            const statusIcon = task.status === 'completed' ? 'check-circle' : 
                             task.status === 'failed' ? 'x-circle' : 'clock';
            
            html += `
                <div class="card mb-2">
                    <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong>${taskId}</strong>
                                <span class="badge bg-${statusClass} ms-2">
                                    <i class="bi bi-${statusIcon}"></i> ${task.status}
                                </span>
                            </div>
                        </div>
                        ${task.result ? `<small class="text-muted">结果: ${JSON.stringify(task.result).substring(0, 100)}...</small>` : ''}
                        ${task.error ? `<small class="text-danger">错误: ${task.error}</small>` : ''}
                    </div>
                </div>
            `;
        }
        
        tasksList.innerHTML = html;
    } catch (error) {
        showStatus(`获取任务列表失败: ${error.message}`, 'danger');
    }
}

// 手动重载数据
async function manualReload() {
    try {
        const response = await fetch('/api/reload', {
            method: 'POST'
        });
        
        const result = await response.json();
        if (result.success) {
            showStatus(result.message, 'success');
        } else {
            showStatus(`重载失败: ${result.error}`, 'danger');
        }
    } catch (error) {
        showStatus(`请求失败: ${error.message}`, 'danger');
    }
}

// 页面加载时刷新任务列表
document.addEventListener('DOMContentLoaded', function() {
    refreshTasks();
    
    // 每5秒自动刷新任务列表
    setInterval(refreshTasks, 5000);
});
</script>

{% endblock %}